package com.guigusuqi.admin.config;

import com.guigusuqi.admin.handler.MyAccessDeniedHandler;
import com.guigusuqi.admin.handler.MyAuthenticationEntryPoint;
import com.guigusuqi.app.config.WxAuthenticationTokenFilter;
import com.guigusuqi.app.config.WxCodeAuthenticationProvider;
import com.guigusuqi.app.config.WxCodeAuthenticationSecurityConfig;
import com.guigusuqi.app.service.impl.WxUserDetailsServiceImpl;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import javax.annotation.Resource;

@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true)//开启权限注解
public class SecurityConfig extends WebSecurityConfigurerAdapter
{
    @Resource
    private WxAuthenticationTokenFilter wxAuthenticationTokenFilter;

    @Resource
    private WxCodeAuthenticationSecurityConfig wxCodeAuthenticationSecurityConfig;

    //认证异常处理
    @Resource
    private MyAuthenticationEntryPoint myAuthenticationEntryPoint;

    //授权异常处理
    @Resource
    private MyAccessDeniedHandler myAccessDeniedHandler;

    @Bean
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception
    {
        return super.authenticationManagerBean();
    }

    @Bean
    public PasswordEncoder passwordEncoder()
    {
        return new BCryptPasswordEncoder();
    }


    /**
     * anyRequest          |   匹配所有请求路径
     * access              |   SpringEl表达式结果为true时可以访问
     * anonymous           |   匿名可以访问
     * denyAll             |   用户不能访问
     * fullyAuthenticated  |   用户完全认证可以访问（非remember-me下自动登录）
     * hasAnyAuthority     |   如果有参数，参数表示权限，则其中任何一个权限可以访问
     * hasAnyRole          |   如果有参数，参数表示角色，则其中任何一个角色可以访问
     * hasAuthority        |   如果有参数，参数表示权限，则其权限可以访问
     * hasIpAddress        |   如果有参数，参数表示IP地址，如果用户IP和参数匹配，则可以访问
     * hasRole             |   如果有参数，参数表示角色，则其角色可以访问
     * permitAll           |   用户可以任意访问
     * rememberMe          |   允许通过remember-me登录的用户访问
     * authenticated       |   用户登录后可访问
     */
    @Override
    protected void configure(HttpSecurity http) throws Exception
    {
        http.apply(wxCodeAuthenticationSecurityConfig);

        http    //关闭防止csrf攻击
                .csrf().disable()
                //不通过session获取SecurityContext
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);

        http
                .authorizeRequests()
                //登录接口可以不用登录进行访问
//                .antMatchers("/login").permitAll()
//                .antMatchers("/druid/**").permitAll()
//                .antMatchers("/doc.html","/webjars/**","/img.icons/**","/swagger-resources/**","/v2/api-docs").permitAll() //允许所有人访问knife4j
//                //authenticated()要求在执行该请求时，必须已经登录了应用。
//                //如果用户没有认证的话，Spring Security的Filter将会捕获该请求，并将用户重定向到应用的登录页面。
//                .antMatchers("/info").authenticated()
                .antMatchers("/wxLogin/**").permitAll()


                .antMatchers("/yy/registration/index/**").permitAll()
                .antMatchers("/payment/registration-order/**").permitAll()
                .antMatchers("/yy/registration/**").permitAll()
                .antMatchers("/api/pay/callback/**").permitAll() // 支付回调
                .antMatchers("/app/pay-user-order-registration/paySuccess/**").permitAll() // 监测是否支付成功


                // 所有用户均可访问的资源,如果原来配置中没有将"/js/**"的路径添加到配置中，会导致没有验证的用户没有权限访问。
                .antMatchers("/css/**", "/js/**","/images/**", "/webjars/**", "**/favicon.ico", "/index").permitAll()
                .antMatchers("/error/**").permitAll()
                .antMatchers("/getUserInfo/**").anonymous()
                .antMatchers("/wxcallback/**").permitAll()
//                .antMatchers("/wxcallback").anonymous()
//                .antMatchers("/getUserInfo/**").anonymous()
                .antMatchers("/doc.html","/webjars/**","/img.icons/**","/swagger-resources/**","/v2/api-docs").permitAll() //允许所有人访问knife4j

                //其他接口需要OncePerRequestFilter子类设置把authenticationToken设置到SecurityContextHolder中才能通过认证
                //（1.登录，2.拦截器填充authenticationToken到securityContextHolder中）
                //SecurityContextHolder.getContext().setAuthentication(authenticationToken);
                .anyRequest().authenticated();

//        //类似于使用了aop思想的拦截器
        http    //把token校验过滤器添加到过滤器链中
                .addFilterBefore(wxAuthenticationTokenFilter, UsernamePasswordAuthenticationFilter.class);

        http.exceptionHandling()
                .authenticationEntryPoint(myAuthenticationEntryPoint)
                .accessDeniedHandler(myAccessDeniedHandler);

        http.cors();
    }
}
